package com.movitech.mobile.base.config;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyDateFormat extends DateFormat {

    private DateFormat dateFormat;

    private SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

    public MyDateFormat(SimpleDateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        return dateFormat.format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        Date date = null;
        try {
            date = format1.parse(source, pos);
        } catch (Exception e1) {
            try{
                date =  format2.parse(source,pos);
            }catch (Exception e2){
                date = dateFormat.parse(source, pos);
            }
        }

        return date;
    }

    @Override
    public Date parse(String source) throws ParseException {
        Date date = null;
        try {
            int length = source.length();
            if(length<=10)
                date =  format2.parse(source);
            else
                date = format1.parse(source);
        } catch (Exception e1) {
            date = dateFormat.parse(source);
        }

        return date;
    }

    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new MyDateFormat((SimpleDateFormat) format);
    }
}